import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import useUserStore from '@/store/modules/user';
import { isRelogin } from '@/utils/request';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/register'];

router.beforeEach((to, from, next) => {

    NProgress.start();
    document.title = <string>to.meta.title;
    /*有登录*/
    if (getToken()) {
        useUserStore().getInfo().then(() => {
            isRelogin.show = false;
            next();
        }).catch((err) => {
            /*token失效或不存在*/
            useUserStore()
                .logOut()
                .then(() => {
                    ElMessage.error(err);
                    isRelogin.show = true;
                    next();
                });
        });
    } else {
        /*如果需要登录 滚去登录*/
        if (to.meta.auth) {
            isRelogin.show = true;
            ElMessage.warning('请先登录');
            isRelogin.redirect = to.fullPath;
            next(`/index?redirect=${to.fullPath}`);
        } else {
            next();
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});
